var express = require('express');
var router = express.Router();
let {
  userModel,
  cateModel,
  starModel,
  addressModel,
  listModel,
  dingdanModel,
  shoucangModel,
  ContextModel,
  ChatModel
}=require('../model/model')
const crypto = require("crypto"); //引入加密模块
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
//引入阿里云短信服务模块
const SMSClient = require('@alicloud/sms-sdk');
//引入jwt模块
const jwt=require('jsonwebtoken')
// let multiparty = require("multiparty");
let AlipaySdk = require("alipay-sdk").default;


//引入阿里云短信服务模块
let AlipaySdkFormData = require("alipay-sdk/lib/form").default;

//加密密码
function md5Password(password){
  const md5=crypto.createHash('md5')
  return md5.update(password).digest('hex')
}
router.post('/adduser',(req,res)=>{
  //加密密码
  userModel.create(req.body)
  res.send({
    code:200,
    msg:'用户添加成功'
  })
})

// 登录
router.post('/login',async(req,res)=>{
  let {phone,password}=req.body
  console.log(password);
  
  let enycryptedPassword=md5Password(password)
  console.log(enycryptedPassword);
  const users=await userModel.find({phone})
  const data=await userModel.find({phone})
  
  //生成token
  let token=jwt.sign({phone},'token',{expiresIn:'1d'})
  console.log(users);
  if(users.length>0){
    res.send({
      code:200,
      msg:'登录成功',
      data:data[0],
      token
    })
  }else{
    res.send({
      code:400,
      msg:'用户名或密码错误'
    })
  }
})


//人脸登录
const IaiClient = tencentcloud.iai.v20200303.Client;
router.post('/rllogin', async (req, res) => {
  let { b64 } = req.body
  // console.log(b64);
  if (b64) {
      const clientConfig = {
          credential: {
              secretId: "AKIDIPL3WlodE0awAF7nERPGvLXXPCpRs5BB",//腾讯云账号的secretId
              secretKey: "ykOwTqDRSHtMdiaGm6EQgu4A6rgO0X0J",//腾讯云账号的secretKey
          },
          region: "ap-beijing",
          profile: {
              httpProfile: {
                  endpoint: "iai.tencentcloudapi.com",
              },
          },
      };
      const client = new IaiClient(clientConfig);
      const params = {
          "GroupIds": [
              "100039802084"//   人脸库ID
          ],
          "Image": b64,// 人脸图片的base64编码
          "MaxFaceNum": 1,// 最多返回人脸数
          "MinFaceSize": 80,// 最小人脸大小
          "MaxPersonNum": 5,// 最多返回人脸数
          "NeedPersonInfo": 1,// 0：不需要返回人员库信息；1：需要返回人员库信息
          "QualityControl": 0,// 0：不进行质量检测；1：进行质量检测
          "FaceMatchThreshold": 0// 人脸相似度阈值
      };

      client.SearchFaces(params).then(
          (doc) => {
              let personName = doc.Results[0].Candidates[0].Score > 80 ? doc.Results[0].Candidates[0].PersonName : null

              //生成token
              if (personName !== null) {
                  let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })
                  res.send({
                      code: 200,
                      msg: "登录成功！",
                      token
                  })
              } else {
                  res.send({
                      code: 201,
                      msg: "识别度过低",
                  })
              }
          },
          (err) => {
              res.send({
                  code: 401,
                  msg: '人脸库无此人！'
              })
              console.error("error", err);
              return false
          }
      )
  } else {
      let { username, password } = req.body
      let indexs = await userModel.find({ phone:username })
      if (indexs.length != 0) {
          let token = jwt.sign({ "name": username }, "face", { expiresIn: '1d' })
          res.send({
              code: 200,
              msg: "登录成功！",
              token
          })
      } else {
          res.send({
              code: 401,
              msg: '用户名或密码错误！'
          })
      }
  }
})


// 产生6位随机数（收到的验证码）
function getCode() {
  let str = "";
  for (let i = 0; i < 6; i++) {
      str += parseInt(Math.random() * 10)
  }
  return str;
}
// 发送短信验证码
router.post('/get_sms', function (req, res, next) {
  let phoneNum = req.body.phone;  //获取前端参数phone
  console.log(phoneNum);
  
  //初始化sms_client
  let smsClient = new SMSClient({
      accessKeyId: 'LTAI5tNyV4AgwZVctwqgA5mS',  //自己阿里云的accessKeyId
      secretAccessKey: 'Gkn7v3b70lxOn5fRykvgwvIX2jjtjH'  //自己阿里云的secretAccessKey
  });

  // 获取6位随机数
  let str = getCode();

  // 开始发送短信
  smsClient.sendSMS({
      PhoneNumbers: phoneNum,
      SignName: "yun2230", //签名名称,阿里云注册
      TemplateCode: "SMS_305050476", //模版CODE,阿里云注册 
      TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
  }).then(r => {
      console.log('执行成功');

      let { Code } = r;
      if (Code == 'OK') {
          res.send({
              code: 200,
              msg: 'success',
              sms: str
          })
          
      }
  })
  .catch(err => {
      res.send({
          code: 400,
          err
      })
  })
});

//注册
router.post('/register',async(req,res)=>{
    let {phone,password}=req.body
    console.log(username,password);
    let enycryptedPassword=md5Password(password)
    let data=await userModel.find({phone})
    console.log(data);
    
    if(data.length>0){
      res.send({
        code:400,
        msg:'用户名已存在'
      })
    }else{
      await user.create({phone,password:enycryptedPassword})
      res.send({
        code:200,
        msg:'注册成功'
      })
    }
  })
 
//修改密码
router.post('/updatePassword',async(req,res)=>{
    let {phone,password}=req.body
    let enycryptedPassword=md5Password(password)
    await userModel.updateOne({phone},{password:enycryptedPassword})
    res.send({
      code:200,
      msg:'修改成功'
    })
})
router.post('/updatePassword2',async(req,res)=>{
    let {_id,password}=req.body
    let enycryptedPassword=md5Password(password)
    await userModel.updateOne({_id},{password:enycryptedPassword})
    res.send({
      code:200,
      msg:'修改成功'
    })
})

//沙箱支付
router.post('/zhifu',async(req,res)=>{
  let {name,price}=req.body
  const alipaySdk = new AlipaySdk({
		// 设置应用 ID
		appId: '2021000142699189',
		// 设置应用私钥
		privateKey: "MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCJsRWGE+xNN0CUXUlBw1M7jLNGs1EfbDUjaI+dbg05s1elEzzShDRBp84dEOzEYktWcQFFinQYqsIiCt+IxQeOrg2n6kzVbHcdC4xD5pt1QQ+tywegBFTDD0y1Z5nz/worznHmZqJNbd7uONpy73S0ELMx9B+lGx+tqoK6E5NBIKO1D8h8CBNnkCC7b+ZtkOLJ2Mymjsk/T+cTYXOdWQ3X8FT+VJpzlPvUHH2QpCu6pGjO55yAfCjBQc/4BjCUEI14jP/hL+iOGevf4GpBD1IGLXgYfkMF9GlpWZAy/L+JYN0xtzLK9RE7xxGLl2kVxC1UiltHuUf7ziAGMokaAY55AgMBAAECggEAImn8MzKvkO0KWwql0KX9G5kjBbyzveL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Np6w5iVfZtvcw25yhwAIUCavJdf3CPrEaAbHtwgvnFeXBEPZs85YlSrjG8Fjht4K7INDWAZUo28a9XNg6bJrEs=",
		// 设置支付宝公钥
		alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnyI4BFVvafyD0RhtMYFZAE6/xs1CFtIR7wPySpLIjDixTob/6+rmE74j65WE6mugX0QzoWUu0xltOJUzdKvjg11pKe+Vp6YE0evOsom/Cy28awWM6rx5VQBJ6ZJ0YfWcTWxKuQDz84zlbj2jz8nT0cuURFR2UF8wbSNiaS27Kit8P9MXZq1NQbCVlxgq9n5ALAO1zKHXNd1BKmqPSUVp91apLbY02cqYdtGW/MelEfO0LkO7C/zfKhShZHxP1kJC0JSGsHjXPcoP4V4em3jekVqEnTqePZq5Fpiy+TRvO1md+JG+whIuZM8RGyS/6+vwk9ioAYzHkNtjVU3xxMaBkwIDAQAB",
		// 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
		// keyType: 'PKCS1',
		// 设置网关地址，默认是 https://openapi.alipay.com
		// endpoint: 'https://openapi.alipay.com',
		gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do", //支付宝网关
	});
	const formData = new AlipaySdkFormData();
	// 同步通知  支付成功之后打开前端的某一个路由
	formData.addField("returnUrl", "http://localhost:5173/home/shouye")
	//支付参数
	formData.addField("bizContent", {
		out_trade_no: Date.now(), //订单编号 一个订单号只能支付一次 不能重复支付
		product_code: "FAST_INSTANT_TRADE_PAY",
		subject: name,
		body: "详情数据", //商品详情
		total_amount: price
	})
	//请求支付宝的第三方接口

	// pc端支付 alipay.trade.page.pay
	// H5端支付 alipay.trade.wap.pay
	let result = await alipaySdk.exec("alipay.trade.wap.pay", {}, {
		formData: formData
	})
  // 修改数据库的信息  将你们的订单信息存储起来
  res.send({
    code:200,
    msg:'支付成功',
    url:result
  })
})

router.post('/addcate',(req,res)=>{
    cateModel.create(req.body)
    res.send({
        msg:'分类添加成功'
    })
})

router.post('/addstar',(req,res)=>{
    starModel.create(req.body)
    res.send({
        msg:'明星添加成功'
    })
})

router.post('/addaddress',(req,res)=>{
    addressModel.create(req.body)
    res.send({
        code:200,
        msg:'地址添加成功'
    })
})

router.post('/addlist',(req,res)=>{
    listModel.create(req.body)
    res.send({
        msg:'商品添加成功'
    })
})

router.post('/adddingdan',(req,res)=>{
    dingdanModel.create(req.body)
    res.send({
        msg:'订单添加成功'
    })
})

router.post('/addshoucang',(req,res)=>{
    shoucangModel.create(req.body)
    res.send({
        msg:'收藏添加成功'
    })
})

router.post('/addcontext',(req,res)=>{
    ContextModel.create(req.body)
    res.send({
        msg:'评论添加成功'
    })
})

router.get('/getcate',async(req,res)=>{
  let data=await cateModel.find()
  res.send({
    code:200,
    data:data
  })
})

router.get('/getstar',async(req,res)=>{
  let data=await starModel.find()
  res.send({
    code:200,
    data:data
  })
})

router.get('/getaddress',async(req,res)=>{
  let data=await addressModel.find()
  res.send({
    code:200,
    data:data
  })
})

router.get('/getlist',async(req,res)=>{
  let {page,pagesize}=req.query
  let data=await listModel.find().limit(Number(pagesize)).skip((Number(page)-1)*Number(pagesize))
  res.send({
    code:200,
    data:data
  })
})

router.get('/getlist2',async(req,res)=>{
  let data=await listModel.find()
  res.send({
    code:200,
    data:data
  })
})

router.get('/getdingdan',async(req,res)=>{
  let data=await dingdanModel.find()
  res.send({
    code:200,
    data:data
  })
})

router.get('/getshoucang',async(req,res)=>{
  let data=await shoucangModel.find()
  res.send({
    code:200,
    data:data
  })
})

router.get('/getcontext',async(req,res)=>{
  let data=await ContextModel.find()
  res.send({
    code:200,
    data:data
  })
})

router.post('/deldingdan',async(req,res)=>{
  let {_id}=req.body
  await dingdanModel.deleteOne({_id})
  res.send({
    code:200,
    msg:'订单删除成功'
  })
})

router.get('/findlist',async(req,res)=>{
  let {_id}=req.query
  let data=await listModel.find({_id})
  let data2=await listModel.find({_id})
  res.send({
    code:200,
    data:data[0],
    data2:data2[0].star
  })
}
)

router.post('/updateuser',async(req,res)=>{
  let {_id,username,name,email,phone}= req.body
  await userModel.updateOne({_id},{username,name,email,phone})
  let data=await userModel.find({_id})
  res.send({
    code:200,
    msg:'用户信息修改成功',
    data:data[0]
  })
})


router.post('/deladdress',async(req,res)=>{
  let {_id}=req.body
  await addressModel.deleteOne({_id})
  res.send({
    code:200,
    msg:'地址删除成功'
  })
})

router.get('/chat', async (req, res) => {
  let list = await ChatModel.find()
  res.send({
    list
  })
})

router.post('/chat',(req,res) => {

  ChatModel.create(req.body)

  res.send({code:200})
})
module.exports = router;
